<template>
  <MesBox
    v-model="visible"
    title="退料单（新建）"
    :width="1000"
    :height="600"
    :onModelClose="clearForm"
  >
    <MesForm
      ref="myform"
      :formFields="formFields"
      :formRules="formRules"
    ></MesForm>
    <MesHeader title="退料明细" icon="el-icon-s-grid">
      <template #default>
        <div style="text-align: right; padding-top: 4px">
          <el-button size="small" link class="textColor" @click="addRow"
            ><i class="el-icon-plus" style="margin-right: 5px"></i
            >添加行</el-button
          >
          <el-button size="small" link class="textColor" @click="delRow"
            ><i class="el-icon-delete" style="margin-right: 5px"></i
            >删除行</el-button
          >
        </div>
      </template>
    </MesHeader>
    <MesTable
      index
      edit
      clickEdit
      ref="mytable"
      :tableData="tableData"
      :columns="columns"
    ></MesTable>
    <template #footer>
      <el-button type="warning" @click="print">
        <i class="el-icon-printer"></i>
        打印</el-button
      >
      <el-button type="danger" @click="save">
        <i class="el-icon-check"></i>
        保存</el-button
      >
    </template>
  </MesBox>
</template>

<script setup>
import { ref, getCurrentInstance, nextTick } from 'vue'
import MesBox from '@/components/basic/MesBox.vue'
import MesForm from '@/components/basic/MesForm.vue'
import MesTable from '@/components/basic/MesTable.vue'
import MesHeader from '@/components/basic/MesHeader.vue'

const emit = defineEmits(['parentCall'])
const that = getCurrentInstance().appContext.config.globalProperties
const mytable = ref(null)
const myform = ref(null)
let visible = ref(false)
let tableData = ref([])
let Material = ref([])
let formFields = ref({
  ReturnProductCode: '',
})
const formRules = [
  [
    {
      title: '订单号',
      field: 'ReturnProductCode',
      type: 'select',
      dataKey: 'orderNum',
      required: true,
      onChange: async (value) => {
        if (value !== '') {
          let res = await that.http.get(
            `/api/Production_WorkOrder/GetBOMMatrail?MoCode=${value}`,
            null,
            true
          )
          columns.value[0].bind.data = res.map((item) => {
            return {
              key: item.productCode,
              value: item.productCode,
            }
          })
          Material.value = res

          tableData.value = tableData.value.map((item) => {
            return {
              ...item,
              ProductCode: '',
              ProductName: '',
              ProductStandard: '',
              Unit: ''
            }
          })
        }
      },
    },
  ],
]

const columns = ref([
  {
    title: '产品编码',
    field: 'ProductCode',
    required: true,
    edit: {
      type: 'select',
    },
    bind: {
      key: '',
      data: [],
    },
    onChange: ({ ProductCode, elementIndex }) => {
      if (ProductCode !== '') {
        let result = Material.value.find(
          (item) => item.productCode == ProductCode
        )
        tableData.value[elementIndex].ProductName = result.productName
        tableData.value[elementIndex].ProductStandard = result.productStandard
        tableData.value[elementIndex].MatType = result.sType
        tableData.value[elementIndex].Unit = result.unit_Id
      }
    },
  },
  {
    title: '产品名称',
    field: 'ProductName',
    disabled: true,
  },
  {
    title: '产品规格',
    field: 'ProductStandard',
    disabled: true,
  },
  {
    title: '单位',
    field: 'Unit',
    disabled: true,
    bind: {
      key: 'unitList',
    },
  },
  {
    title: '退料人',
    field: 'ReturnMaterialsMan',
    required: true,
    edit: {
      type: 'input',
    },
  },
  {
    title: '退料数量',
    field: 'ReturnMaterialsQnty',
    required: true,
    edit: {
      type: 'number',
    },
  },
  {
    title: '备注',
    field: 'Remark',
    edit: {
      type: 'input',
    },
  },
  {
    title: '类别',
    field: 'MatType',
    hidden: true,
  },
])

const open = () => {
  visible.value = true
}

const save = async () => {
  let flag = validateTable()
  if (flag) {
    let res = await that.http.post(
      '/api/Ware_ReturnMaterials/InsertReturnMaterials',
      {
        RMlist: tableData.value,
      },
      true
    )

    if (res.status) {
      that.$message.success('新建成功')
      visible.value = false
      clearForm()
      emit('parentCall', ($parent) => {
        $parent.search()
      })
    } else {
      that.$message.error(res.message)
    }
  }
}

const addRow = () => {
  mytable.value.tableData.push({})
}

const delRow = () => {
  mytable.value.delRow()
}

const clearForm = () => {
  formFields.value = {
    ReturnProductCode: '',
  }
  tableData.value = []
}

const print = () => {
  let flag = validateTable()
  console.log(flag)
  if (flag) {
    let data = {
      mainData: {
        ReturnProductCode: formFields.value.ReturnProductCode,
      },
      detailData: tableData.value,
    }

    emit('parentCall', ($parent) => {
      $parent.print(data)
    })
  }
}

//验证table
const validateTable = () => {
  try {
    let flag = true
    if (!formFields.value.ReturnProductCode) {
      flag = false
      throw new Error('请选择退料单号')
    }

    if (tableData.length == 0) {
      flag = false
      throw new Error('请填写退料明细')
    }
    tableData.value = tableData.value.map((item) => {
      if (!item.hasOwnProperty('ProductCode') || item.ProductCode == '') {
        throw new Error('请选择产品')
      }

      if (
        !item.hasOwnProperty('ReturnMaterialsMan') ||
        item.ReturnMaterialsMan == ''
      ) {
        throw new Error('请填写退料人')
      }

      if (
        !item.hasOwnProperty('ReturnMaterialsQnty') ||
        item.ReturnMaterialsQnty == ''
      ) {
        throw new Error('请填写退料数量')
      }

      return {
        ...item,
        ReturnProductCode: formFields.value.ReturnProductCode,
      }
    })

    return flag
  } catch (error) {
    that.$message.error(error.message)
    return false
  }
}

defineExpose({ open })
</script>

<style lang="scss" scoped></style>
